package com.snap.vseries.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.snap.vseries.R;
import com.snap.vseries.adapter.CommenPagerAdapter;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.base.BaseFragment;
import com.snap.vseries.fragment.HistoryFragment;
import com.snap.vseries.fragment.HomeFragment;
import com.snap.vseries.fragment.MyFragment;
import com.snap.vseries.utils.OkHttpUtil;
import com.snap.vseries.ui.widget.CustomViewPager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class HomeActivity extends BaseActivity {
    @BindView(R.id.tab_layout)
    public TabLayout tabLayout;
    @BindView(R.id.view_pager)
    CustomViewPager viewPager;
    @BindView(R.id.time_tv)
    TextView timeTv;
    /**
     * 广播注册标识
     */
    private boolean mReceiverTag = false;
    private ArrayList<BaseFragment> fragmentList = new ArrayList<>();
    private String[] tabArr = new String[]{"实验", "报告", "设备"};
    private int[] tabBgSelectedArr;
    private int[] tabBgUnSelectedArr;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy - MM - dd  HH : mm", Locale.CHINA);
    private BroadcastReceiver systemTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            refreshSystemTime();
        }
    };

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, HomeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_home;
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        registerSystemTimeBoardCast();
    }


    private void registerSystemTimeBoardCast() {
        IntentFilter timeFilter = new IntentFilter();
        timeFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(systemTimeReceiver, timeFilter);
        mReceiverTag = true;
        refreshSystemTime();
    }

    private void refreshSystemTime() {
        timeTv.setText(format.format(new Date()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (systemTimeReceiver != null && mReceiverTag) {
            unregisterReceiver(systemTimeReceiver);
        }
    }

    private void initView() {
        fragmentList.add(new HomeFragment());
        fragmentList.add(new HistoryFragment());
        fragmentList.add(new MyFragment());
//        fragmentList.add(new WebFragment());
        viewPager.setOffscreenPageLimit(3);
        //禁止滑动
        viewPager.setScanScroll(false);
        //切换时取消动画效果
        viewPager.setChangeItemAnim(false);
        viewPager.setAdapter(new CommenPagerAdapter(getSupportFragmentManager(), fragmentList));
        initTabLayout();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        fragmentList.get(0).setUserVisibleHint(true);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            String FRAGMENTS_TAG = "android:support:fragments";
            savedInstanceState.remove(FRAGMENTS_TAG);
        }
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void initTabLayout() {
        tabBgSelectedArr = new int[]{R.drawable.icon_home_focused, R.drawable.icon_history_focused, R.drawable.icon_device_focused, R.drawable.icon_web_focused};
        tabBgUnSelectedArr = new int[]{R.drawable.icon_home, R.drawable.icon_history, R.drawable.icon_device, R.drawable.icon_web};
        //MODE_FIXED标签栏不可滑动，各个标签会平分屏幕的宽度（TabLayout.MODE_SCROLLABLE可滑动）
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        //关联tabLayout和ViewPager,两者的选择和滑动状态会相互影响
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setTab(tabLayout.getSelectedTabPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        //自定义标签布局,先设置addOnTabSelectedListener 监听器，再添加Tab
        setTab(0);
    }

    public void setTab(int index) {
        for (int i = 0; i < tabArr.length; i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);

            View tabView = tab.getCustomView();
            if (tabView == null) {
                tabView = LayoutInflater.from(this).inflate(R.layout.tabview_home, tabLayout, false);
            }
            ((TextView) (tabView.findViewById(R.id.text_view))).setText(tabArr[i]);
            if (i == index) {
                //默认选中第一个tab
                (tabView.findViewById(R.id.image_view)).setBackgroundResource(tabBgSelectedArr[i]);
                ((TextView) (tabView.findViewById(R.id.text_view))).setTextColor(0xFF568BFF);
            } else {
                (tabView.findViewById(R.id.image_view)).setBackgroundResource(tabBgUnSelectedArr[i]);
                ((TextView) (tabView.findViewById(R.id.text_view))).setTextColor(0xFFC1C3CF);
            }
            tab.setCustomView(tabView);
        }
    }
}

